import React, { useEffect } from 'react'
import './index.less'
import logo from "@/assets/images/logo.png"
import { routes } from '@/routes'
import { Link, useLocation } from 'react-router-dom'

import {
    AppstoreOutlined,
} from '@ant-design/icons';
import { Menu } from 'antd';

export default function SiderNav(props) {
    function getItem(label, key, icon, children, type) {
        return {
            key,
            icon,
            children,
            label,
            type
        };
    }

    let routerTitles = []
    let routeTitle = ""
    const { pathname } = useLocation()

    useEffect(() => {
        getRouteTitle()
        props.editRouteTitle(routeTitle)
    });

    // let items = [
    //     getItem(<div>首页</div>, '1', <PieChartOutlined />,),
    //     getItem('商品', 'sub1', <MailOutlined />, [
    //         getItem('品类管理', '5'),
    //         getItem('商品管理', '6'),
    //     ]),
    //     getItem('用户管理', '2', <DesktopOutlined />),
    //     getItem('角色管理', '3', <ContainerOutlined />),
    //     getItem('图形图表', 'sub2', <AppstoreOutlined />, [
    //         getItem('Option 9', '9'),
    //         getItem('Option 10', '10'),
    //         getItem('Submenu', 'sub3', null, [getItem('Option 11', '11'), getItem('Option 12', '12')]),
    //     ]),
    // ];

    function getRouteTitle() {
        for (const iterator of routerTitles) {
            if (iterator.key.includes(pathname)) {
                routeTitle = iterator.title
                break
            }
        }
    }

    function routingTables() {
        function addRoute(objRouter = {}) {
            let children = undefined
            const { path = "", title = "" } = objRouter
            const label = <Link to={path} children={title} />
            const el = getItem(label, path, <AppstoreOutlined />)
            el.title = title

            for (const key in objRouter) {
                if (Object.hasOwnProperty.call(objRouter, key)) {
                    if (key === "children") {
                        children = childrenDeep(objRouter[key])
                    }
                }
            }

            routerTitles.push(el)
            return { ...el, children }
        }

        const { children = [] } = routes.find(e => e.path.includes("admin"))

        const childrenDeep = childrenArr => childrenArr.map(item => addRoute(item))

        return childrenDeep(children)
    }

    return (
        <div className='SiderNav'>
            <div className='logo'>
                <div className='logo_img'>
                    <img src={logo} alt="logo" />
                </div>

                <h1>硅谷后台</h1>
            </div>

            <Menu
                defaultSelectedKeys={[pathname]}
                defaultOpenKeys={[pathname]}
                mode="inline"
                theme="dark"
                items={routingTables()}
            />
        </div>
    )
}
